//
//  Networking.m
//  DouBan1.0
//
//  Created by Aurora on 15/11/26.
//  Copyright © 2015年 Aurora. All rights reserved.
//

#import "Networking.h"
#import <AFNetworking.h>

@implementation Networking

+ (void)receiveDataWithURLString:(NSString *)string
                          method:(NSString *)method
                            body:(NSString *)body
                           Block:(Block)block {
    

    NSURL *url = [NSURL URLWithString:string];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    [request setHTTPMethod:method];
    
    if ([method isEqualToString:@"POST"]) {
        
        NSData *data = [body dataUsingEncoding:NSUTF8StringEncoding];
        
        [request setHTTPBody:data];
        
    }
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *  response, NSData *  data, NSError *  connectionError) {
        if (data != nil) {
            
            block(data);
        }
        
    }];
}

+(NSString *)filePath:(NSString *)filePaths
                 url :(NSString *)url
             fileName:(NSString *)fileName
          hospital_id:(NSString *)hospital_id
{
    

    NSString *urlStr = [NSString stringWithFormat:@"http://app.hspcn.com/attachments/downloadAttachments?attachId=%@&hospital_id=%@",filePaths,hospital_id];
    NSArray *name = [fileName componentsSeparatedByString:@"."];
    NSURL *url1 = [[NSURL alloc]initWithString:urlStr];
    NSData * audioData = [NSData dataWithContentsOfURL:url1];
    //将数据保存到本地指定位置
    NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@.%@", docDirPath ,name[0],[url lowercaseString]];
    [audioData writeToFile:filePath atomically:YES];
    return filePath;
    
}

+ (NSString *)getLastDayOfMonth
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDate *firstDay;
    [calendar rangeOfUnit:NSCalendarUnitMonth startDate:&firstDay interval:nil forDate:[NSDate date]];
    NSDateComponents *lastDateComponents = [calendar components:NSCalendarUnitMonth | NSCalendarUnitYear |NSCalendarUnitDay fromDate:firstDay];
    NSUInteger dayNumberOfMonth = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:[NSDate date]].length;
    NSInteger day = [lastDateComponents day];
    [lastDateComponents setDay:day+dayNumberOfMonth-1];
    NSDate *lastDay = [calendar dateFromComponents:lastDateComponents];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:lastDay];
    
    NSString *lastDayOfMonth = [NSString stringWithFormat:@"%@",strDate];
    return lastDayOfMonth;
}


+ (NSString *)getCurrentTime {
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *dateTime = [formatter stringFromDate:[NSDate date]];
    return dateTime;
}

+ (NSString *)getOneYearLaterTime:(NSString *)nowtime yearNumber:(CGFloat)yearNumber
{
    
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题
    
    NSDate *birthdayDate = [dateFormatter dateFromString:nowtime];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents *comps = nil;
    
    comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitMonth fromDate:birthdayDate];
    
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    
    [adcomps setMonth:yearNumber * 12];
    
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:birthdayDate options:0];
    
    NSString *beforDate = [dateFormatter stringFromDate:newdate];

    return beforDate;
}


+ (void)ManagerPost:(NSString *)URLString
         parameters:(id)parameters
            success:(void (^)(id responseObject))success
            failure:(void (^)(NSError *error))failure {
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
    
    [manager POST:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([[responseObject objectForKey:@"flag"] isEqual:[NSNumber numberWithInt:1]]) {
            
            success(responseObject);
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"%@",error);
    }];
    
}

+ (void)ManagerGet:(NSString *)URLString
        parameters:(id)parameters
           success:(void (^)(id))success
           failure:(void (^)(NSError *))failure
{
 
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/plain",nil];
    
    [manager GET:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        success(responseObject);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"error=%@",error);
    }];
    
    
    
//    [manager POST:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
//
//
//
//
//        if ([[responseObject objectForKey:@"flag"] isEqual:[NSNumber numberWithInt:1]]) {
//
//            success(responseObject);
//        }
//
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//
//        NSLog(@"%@",error);
//    }];

}


+ (UIColor *)colorWithHexString:(NSString *)stringToConvert

{
    
    if ([stringToConvert hasPrefix:@"#"])
        
    {
        
        stringToConvert = [stringToConvert substringFromIndex:1];
        
    }
    
    
    NSScanner *scanner = [NSScanner scannerWithString:stringToConvert];
    
    unsigned hexNum;
    
    if (![scanner scanHexInt:&hexNum])
        
    {
        
        return nil;
        
    }
    
    return [self colorWithRGBHex:hexNum];
    
}

+ (UIColor *)colorWithRGBHex:(UInt32)hex

{
    
    int r = (hex >> 16) & 0xFF;
    
    int g = (hex >> 8) & 0xFF;
    
    int b = (hex) & 0xFF;
    
    
    
    return [UIColor colorWithRed:r / 255.0f
            
                           green:g / 255.0f
            
                            blue:b / 255.0f
            
                           alpha:1.0f];
    
}

+ (NSDictionary *)getStatusWithUrl:(NSString *)Url
{
    NSURL *set = [NSURL URLWithString:Url];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:set
                                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                                         timeoutInterval:2.0f];
    NSHTTPURLResponse *response = nil;
    
    NSError *error = nil;
    
    NSData *data = [NSURLConnection sendSynchronousRequest:request
                                         returningResponse:&response
                                                     error:&error];

    if (data) {
        
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        
        if (dataDic) {
            
            NSDictionary *dic = @{@"dataDic":dataDic,
                                  @"stateCode":@([response statusCode])
                                  };
            return dic;

        }
        
    }else {
        
        return nil;
    }
    return nil;
}

@end
